package com.kob.backend.controller.user.account;

import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.User;
import com.kob.backend.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
//@RequestMapping("/api")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    // 获取当前登录的用户用户名
    @GetMapping("/user/account/currentUser")
    public ResponseEntity<Map<String, Object>> getCurrentUser(HttpServletRequest request) {
        // 从请求头部获取JWT令牌
        String token = request.getHeader("Authorization");
        if (null != token && !token.trim().isEmpty()) {
            // 解析JWT令牌，获取用户信息
            String userid = JwtUtil.extractUsername(token.replace("Bearer","").trim());
            User user = userMapper.selectById(userid);
            String username = user.getUsername();
            // 在这里处理获取到的用户名
            Map<String, Object> response = new HashMap<>();
            response.put("username", username);
            return ResponseEntity.ok(response);
        } else {
            Map<String, Object> response = new HashMap<>();
            response.put("username", null);
            response.put("message", "没传token");
            return ResponseEntity.ok(response);
        }
    }
}

